<template>
  <div class="register-container">
    <el-card class="register-card">
      <div class="register-header">
        <h2>账号注册</h2>
        <p>创建您的在线学习账号</p>
      </div>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            type="email"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
        
        
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="register-button" 
            :loading="loading" 
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-link">
        已有账号? 
        <router-link to="/login">立即登录</router-link>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'RegisterPage',
  setup() {
    const store = useStore()
    const router = useRouter()
    const registerFormRef = ref(null)
    const loading = computed(() => store.state.isLoading)
    
    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      examNumber: '',
      fullName: '',
      phoneNumber: ''
    })
    
    // callback 风格的校验函数，确保不会抛出未捕获 promise
    // 密码确认校验
    const validateConfirmPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    // 手机号校验
    const validatePhone = (rule, value, callback) => {
      if (!value) return callback();
      const phoneReg = /^1[3-9]\\d{9}$/;
      if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, message: '用户名长度不能少于3个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validateConfirmPass, trigger: 'blur' }
      ],
      phoneNumber: [
        { validator: validatePhone, trigger: 'blur' }
      ]
    }
    
    const handleRegister = () => {
      if (!registerFormRef.value) return;
      // 使用 callback 风格校验，并在回调中处理注册逻辑
      registerFormRef.value.validate((valid, fields) => {
        if (valid) {
          // 校验通过，提交注册请求
          const userData = { ...registerForm };
          delete userData.confirmPassword;
          store.dispatch('register', userData)
            .then(result => {
              if (result.success) {
                ElMessage.success('注册成功，请登录');
                router.push('/login');
              } else {
                ElMessage.error(result.message || '注册失败');
              }
            })
            .catch(error => {
              console.error('注册异常:', error);
              ElMessage.error('注册异常，请稍后重试');
            });
        } else {
          console.log('表单校验失败：', fields);
        }
      });
    }
    
    onMounted(() => {
      // 检查是否已经登录
      if (store.getters.isAuthenticated) {
        router.push('/')
      }
    })
    
    return {
      registerForm,
      registerFormRef,
      rules,
      loading,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 0;
  background-color: #f5f7fa;
}

.register-card {
  width: 500px;
  padding: 20px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.register-header p {
  font-size: 14px;
  color: #909399;
}

.register-button {
  width: 100%;
}

.login-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}
</style> 